import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import dts from 'vite-plugin-dts'
import { resolve } from 'path'

// https://vite.dev/config/
export default defineConfig(({mode}) => {
  const env = loadEnv(mode, process.cwd());
  return {
    plugins: [
      vue(),
      vueJsx(),
      dts({
        include: ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.vue'],
        outDir: 'dist/types',
        staticImport: true,
        insertTypesEntry: true,
      }),
    ],
    build: {
      lib: {
        entry: resolve(__dirname, 'src/main.ts'),
        name: 'WMC',
        fileName: (format) => `wmc.${format}.js`,
        formats: ['es', 'umd'],
      },
      rollupOptions: {
        external: ['vue', 'element-plus'],
        output: {
          globals: {
            vue: 'Vue',
            'element-plus': 'ElementPlus',
          },
          assetFileNames: (assetInfo) => {
            if (assetInfo.name === 'style.css') return 'style.css'
            return assetInfo.name
          },
        },
      },
      cssCodeSplit: false,
      sourcemap: true,
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          charset: false
        }
      }
    },
    server: {
      host: "0.0.0.0", // 允许本机IP访问 0.0.0.0
      port: 3000, // 端口号
      hmr: true, // 热更新
      open: true, // 自动打开
      proxy: {
        // 代理跨域
        [env.VITE_WEB_BASE_API as string]: {
          // 配置哪个环境下的
          target: env.VITE_SERVER,
          rewrite: path => path.replace(new RegExp("^" + env.VITE_WEB_BASE_API), ""), // 重写路径
          // 允许跨域
          changeOrigin: true
        }
      }
    },
  }
})
